package com.momoc.mrpc.config;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.momoc.mrpc.annotation.EnabledMRpc;
import java.util.Properties;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

/**
 * @author momoc
 * @version 1.0
 * @className MRpcConfig
 * @description
 * @date 2022/7/25 1:53 下午
 */
@Data
@Component
@ConfigurationProperties(prefix = "mrpc")
@ComponentScan(basePackages = "com.momoc.mrpc")
public class MRpcConfig {
    @Value("${mrpc.mrpc-serialize-mode}")
    String mrpcSerializeMode;

    @Value("${mrpc.register-name}")
    public void getRegisterConfig(String value){
        String registerCenterName = value;
         registerCenter = registerCenterName.substring(0, registerCenterName.indexOf(":"));
         ip = registerCenterName.substring(registerCenterName.indexOf("//") + 2, registerCenterName.lastIndexOf(":"));
        nacosPort = Integer.parseInt(registerCenterName.substring(registerCenterName.lastIndexOf(":") + 1, registerCenterName.length()));
    }
    Integer nacosPort;
    String ip;
    String registerCenter;

    @Value("${server.port}")
    Integer serverPort;

    @Bean
    public NamingService namingService(MRpcConfig mRpcConfig){
        try {
            Properties properties = new Properties();
            properties.setProperty("serverAddr", mRpcConfig.getIp());
            NamingService namingService = NamingFactory.createNamingService(properties);
            return namingService;
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
    }

    @Bean
    public ConfigService configService(MRpcConfig mRpcConfig){
        ConfigService configService = null;
        try {
            configService = NacosFactory.createConfigService(mRpcConfig.getIp());
        } catch (NacosException e) {
            e.printStackTrace();
        }
        return configService;

    }

}
